package edu.gatech.cs2340.aperturescience.backend.task;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import edu.gatech.cs2340.aperturescience.backend.TodoSQLiteHelper;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.util.Log;

/**
 * SQLTasksDataSource manages the Tasks database
 * 
 * @author Aperture Science
 * @3/12/2011
 */
public class SQLTasksDataSource implements TasksDataSource {
	private SQLiteDatabase database;
	private TodoSQLiteHelper dbHelper;

	public SQLTasksDataSource(Context context) {
		dbHelper = new TodoSQLiteHelper(context);
	}

	/**
	 * Opens the database.
	 */
	public void open() throws SQLException {
		if (database == null) {
			database = dbHelper.getWritableDatabase();
		} else if (database.isOpen()) {
			database.close();
			database = dbHelper.getWritableDatabase();
		}
	}

	/**
	 * Closes the database.
	 */
	public void close() {
		if (database != null)
			database.close();
	}

	/**
	 * getTask finds and returns a task based on a database query
	 * 
	 * @param cursor
	 * @return
	 */
	private Task getTask(Cursor cursor) {
		int id = cursor.getInt(0);
		String name = cursor.getString(1);
		String description = cursor.getString(2);
		String category = cursor.getString(3);
		Date date = new Date(cursor.getLong(4));
		boolean completed = cursor.getInt(5) == 1;
		Log.d("X", id + " " + cursor.getInt(5));
		Task task = new Task(id, name, description, category, null, date,
				completed);
		return task;
	}

	/**
	 * getTasks returns a list of Tasks matching a given database query
	 * 
	 * @param cursor
	 * @return
	 */
	private List<Task> getTasks(Cursor cursor) {
		ArrayList<Task> tasks = new ArrayList<Task>();
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Task task = getTask(cursor);
			tasks.add(task);
			cursor.moveToNext();
		}
		return tasks;
	}

	/**
	 * createTask creates a task containing the given information
	 */
	public void createTask(int userID, String name, String description,
			String category, Location location, Date dueDate) {
		ContentValues values = new ContentValues();
		values.put(dbHelper.COLUMN_TASKOWNER, userID);
		values.put(dbHelper.COLUMN_TASKNAME, name);
		values.put(dbHelper.COLUMN_TASKCATEGORY, category);
		values.put(dbHelper.COLUMN_TASKDESCRIPTION, description);
		values.put(dbHelper.COLUMN_DUEDATE, dueDate.getTime());
		values.put(dbHelper.COLUMN_COMPLETED, 0);
		database.insert(dbHelper.TABLE_TASK, null, values);
	}

	/**
	 * createCategory initiates a category from the task creation menu - Only
	 * applicable if in the "All" Category
	 */
	public void createCategory(int userID, String category) {
		ContentValues values = new ContentValues();
		values.put(dbHelper.COLUMN_CATEGORYUSER, userID);
		values.put(dbHelper.COLUMN_CATEGORY, category);
		database.insert(dbHelper.TABLE_TASK, null, values);
	}

	/**
	 * getTaskByName returns a specific task with name matching the given String
	 */
	public Task getTaskByName(String name) {
		Cursor c = database
				.rawQuery(
						"SELECT id,name,description,category,date,completed FROM tasks WHERE name=? LIMIT 1",
						new String[] { "" + name });
		return getTask(c);
	}

	/**
	 * getTaskByID returns a specific task with uniqueID matching the given int
	 */
	public Task getTaskByID(int uniqueID) {
		Cursor c = database
				.rawQuery(
						"SELECT id,name,description,category,date,completed FROM tasks WHERE owner=? LIMIT 1",
						new String[] { "" + uniqueID });
		return getTask(c);
	}

	/**
	 * getCategoryTasks returns a list of tasks under the specified Category
	 */
	public List<Task> getCategoryTasks(int userid, String category) {
		Cursor c = database
				.rawQuery(
						"SELECT id,name,description,category,date,completed FROM tasks WHERE owner= ? AND category=? ORDER BY date DESC	",
						new String[] { "" + userid, category });
		return getTasks(c);
	}

	/**
	 * getTasksByDate returns all tasks within the specified Data parameter
	 */
	@Override
	public List<Task> getTasksByDate(Date dueDate) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * deleteTask delets a task matching the given uniqueID
	 */
	@Override
	public void deleteTasks(int[] uniqueid) {
		if (uniqueid != null) {
			for (int i : uniqueid) {
				database.delete(dbHelper.TABLE_TASK, "id=?", new String[] { ""
						+ i });
			}
		}
	}

	/**
	 * getAllTasks returns a list of all existing Tasks
	 */
	@Override
	public List<Task> getAllTasks(int userID) {
		Cursor c = database
				.rawQuery(
						"SELECT id,name,description,category,date,completed FROM tasks WHERE owner=? ORDER BY date DESC",
						new String[] { "" + userID });
		return getTasks(c);
	}

	@Override
	public void setCompleted(int taskID, boolean completed) {
		Log.d("X", taskID + " " + completed);
		int i = completed ? 1 : 0;
		ContentValues v = new ContentValues();
		v.put(dbHelper.COLUMN_COMPLETED, i);
		database.update(dbHelper.TABLE_TASK, v, dbHelper.COLUMN_ID + "="
				+ taskID, null);
	}
}
